var utils = require("../../utils/utils.js");
var server = require("../../utils/server.js");
var config = require("../../config.js");
var apis = require("../../utils/api.js");

const app = getApp();

Page({

  /** 
   * 页面的初始数据
   */
  data: {
    location: '', //用于存放login返回的地理位置
    wxloginNum: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('startPage，options = ' + JSON.stringify(options))
    this.wxLogin()
  },

  onShow: function () {},

  onUnload: function () {},

  wxLogin: function () {
    this.data.wxloginNum++;
    let _this = this;
    wx.login({
      success: function (res) {
        console.log('wx.login success = ' + JSON.stringify(res));
        _this.login(res);
      },
      fail: function (res) {
        console.log('wx.login fail = ' + JSON.stringify(res))
        if (_this.data.wxloginNum > 3) {
          utils.showToast("微信登录失败，请稍后重试")
        } else {
          _this.wxLogin();
        }
      }
    })
  },

  // //客户登录 获取openid等用户信息
  login: function (res) {
    let _this = this;
    var params = {
      "code": res.code,
      "type": 34,
      "state": 0
    }
    var api = apis.login
    server.postRequest(config.xburl, api, params,
      function (res) {
        try {
          wx.setStorageSync('Token', res.data.accessToken)
        } catch (e) {}
        app.globalData.userId = res.data.userId;
        app.globalData.openid = res.data.openid;
        console.log('login获取用户openid成功', app.globalData.openid)
        _this.getUserInfo()
      },
      function (err) {
        utils.showToast(err)
      })
  },


  //获得登录用户企业信息
  getUserInfo() {
    var _this = this;
    var prams = {
      id: app.globalData.userId
    }
    var api = apis.getUserInfo;
    server.getRequest(config.xburl, api, prams,
      function (res) {
        app.globalData.userInfo.authStatus = res.data.authStatus,
          app.globalData.userInfo.cardNo = res.data.cardNo,
          app.globalData.userInfo.entId = res.data.entId,
          app.globalData.userInfo.nickname = res.data.nickname
        app.globalData.userInfo.avatar = res.data.avatar
        app.globalData.userInfo.mobile = res.data.mobile
        app.globalData.userInfo.userType = res.data.userType
        wx.reLaunch({
          url: '/pages/Main/Main?value=' + JSON.stringify(res.data.authStatus),
        })
      },
      function (err) {
        utils.showToast(err)
      })
  },
})